package ink.tsg.geo.utils;


import org.apache.commons.io.FilenameUtils;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.stream.IntStream;

/**
 * @author geo_tsg
 * @version 1.0.0
 * @ClassName Tif2PngUtile.java
 * @Description
 * @createTime 2021-07-20
 */
public class Tif2PngUtils {

    public static void convertTiffToPng(File file) {
        try {
            try (InputStream is = new FileInputStream(file)) {
                try (ImageInputStream imageInputStream = ImageIO.createImageInputStream(is)) {
                    Iterator<ImageReader> iterator = ImageIO.getImageReaders(imageInputStream);
                    if (iterator == null || !iterator.hasNext()) {
                        throw new RuntimeException("Image file format not supported by ImageIO:" + file.getAbsolutePath());
                    }

                    // We are just looking for the first reader compatible:
                    ImageReader reader = iterator.next();
                    reader.setInput(imageInputStream);

                    int numPage = reader.getNumImages(true);

                    // it uses to put new png files, close to original example n0_.tiff will be in /png/n0_0.png
                    String name = FilenameUtils.getBaseName(file.getAbsolutePath());
                    String parentFolder = file.getParentFile().getAbsolutePath();

                    IntStream.range(0, numPage).forEach(v -> {
                        try {
                            final BufferedImage tiff = reader.read(v);
                            ImageIO.write(tiff,"png", new File(parentFolder +"/"+ name + v +".png"));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    });
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        convertTiffToPng(new File("E:\\工作文档\\管理规范\\测试数据\\济南裕兴化工原厂区多期遥感影像提交版\\20030703.tif"));
    }
}
